#include "usbd_core.h"
#include "usbd_cdc.h"

#include "ch32v30x.h"
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>


/*!< endpoint address */
#define CDC_IN_EP  0x81
#define CDC_OUT_EP 0x02
#define CDC_INT_EP 0x83

#define USBD_VID           0x1234
#define USBD_PID           0x5678
#define USBD_MAX_POWER     100
#define USBD_LANGID_STRING 1033

/*!< config descriptor size */
#define USB_CONFIG_SIZE (9 + CDC_ACM_DESCRIPTOR_LEN)

/*!< global descriptor */
static uint8_t cdc_descriptor[] = {
    USB_DEVICE_DESCRIPTOR_INIT(USB_2_0, 0xEF, 0x02, 0x01, USBD_VID, USBD_PID, 0x0100, 0x01),
    USB_CONFIG_DESCRIPTOR_INIT(USB_CONFIG_SIZE, 0x02, 0x01, USB_CONFIG_BUS_POWERED, USBD_MAX_POWER),
    CDC_ACM_DESCRIPTOR_INIT(0x00, CDC_INT_EP, CDC_OUT_EP, CDC_IN_EP, 0x02),
    ///////////////////////////////////////
    /// string0 descriptor
    ///////////////////////////////////////
    USB_LANGID_INIT(USBD_LANGID_STRING),
    ///////////////////////////////////////
    /// string1 descriptor
    ///////////////////////////////////////
    0x14,                       /* bLength */
    USB_DESCRIPTOR_TYPE_STRING, /* bDescriptorType */
    'C', 0x00,                  /* wcChar0 */
    'h', 0x00,                  /* wcChar1 */
    'e', 0x00,                  /* wcChar2 */
    'r', 0x00,                  /* wcChar3 */
    'r', 0x00,                  /* wcChar4 */
    'y', 0x00,                  /* wcChar5 */
    'U', 0x00,                  /* wcChar6 */
    'S', 0x00,                  /* wcChar7 */
    'B', 0x00,                  /* wcChar8 */
    ///////////////////////////////////////
    /// string2 descriptor
    ///////////////////////////////////////
    0x26,                       /* bLength */
    USB_DESCRIPTOR_TYPE_STRING, /* bDescriptorType */
    'C', 0x00,                  /* wcChar0 */
    'h', 0x00,                  /* wcChar1 */
    'e', 0x00,                  /* wcChar2 */
    'r', 0x00,                  /* wcChar3 */
    'r', 0x00,                  /* wcChar4 */
    'y', 0x00,                  /* wcChar5 */
    'U', 0x00,                  /* wcChar6 */
    'S', 0x00,                  /* wcChar7 */
    'B', 0x00,                  /* wcChar8 */
    ' ', 0x00,                  /* wcChar9 */
    'C', 0x00,                  /* wcChar10 */
    'D', 0x00,                  /* wcChar11 */
    'C', 0x00,                  /* wcChar12 */
    ' ', 0x00,                  /* wcChar13 */
    'D', 0x00,                  /* wcChar14 */
    'E', 0x00,                  /* wcChar15 */
    'M', 0x00,                  /* wcChar16 */
    'O', 0x00,                  /* wcChar17 */
    ///////////////////////////////////////
    /// string3 descriptor
    ///////////////////////////////////////
    0x16,                       /* bLength */
    USB_DESCRIPTOR_TYPE_STRING, /* bDescriptorType */
    '2', 0x00,                  /* wcChar0 */
    '0', 0x00,                  /* wcChar1 */
    '2', 0x00,                  /* wcChar2 */
    '2', 0x00,                  /* wcChar3 */
    '1', 0x00,                  /* wcChar4 */
    '2', 0x00,                  /* wcChar5 */
    '3', 0x00,                  /* wcChar6 */
    '4', 0x00,                  /* wcChar7 */
    '5', 0x00,                  /* wcChar8 */
    '6', 0x00,                  /* wcChar9 */
#ifdef CONFIG_USB_HS
    ///////////////////////////////////////
    /// device qualifier descriptor
    ///////////////////////////////////////
    0x0a,
    USB_DESCRIPTOR_TYPE_DEVICE_QUALIFIER,
    0x00,
    0x02,
    0x02,
    0x02,
    0x01,
    0x40,
    0x01,
    0x00,
#endif
    0x00
};

USB_NOCACHE_RAM_SECTION USB_MEM_ALIGNX uint8_t usb_cdc_read_buffer[2048] = {0};
USB_NOCACHE_RAM_SECTION USB_MEM_ALIGNX uint8_t usb_cdc_write_buffer[2048] = {0};

struct rt_semaphore     cdc_tx_sem = {0};
struct rt_semaphore     cdc_rx_sem = {0};

struct rt_ringbuffer     cdc_rx_ringbuffer = {0};

uint8_t cdc_rx_ringbuffer_pool[1024] = {0};

volatile bool ep_tx_busy_flag = false;

#ifdef CONFIG_USB_HS
#define CDC_MAX_MPS 512
#else
#define CDC_MAX_MPS 64
#endif

void usbd_configure_done_callback(void)
{
    /* setup first out ep read transfer */
    usbd_ep_start_read(CDC_OUT_EP, usb_cdc_read_buffer, 2048);
}

void usbd_cdc_acm_bulk_out(uint8_t ep, uint32_t nbytes)
{
    //USB_LOG_RAW("actual out len:%d\r\n", nbytes);
    //rt_kprintf("out rx len:%d\r\n", nbytes);
    // for (int i = 0; i < 100; i++) {
    //     printf("%02x ", read_buffer[i]);
    // }
    // printf("\r\n");
    /* setup next out ep read transfer */
    usbd_ep_start_read(CDC_OUT_EP, usb_cdc_read_buffer, 2048);
    if(nbytes > 0)
    {
        rt_ringbuffer_put(&cdc_rx_ringbuffer, usb_cdc_read_buffer, nbytes);
        rt_sem_release(&cdc_rx_sem);
    }
}

void usbd_cdc_acm_bulk_in(uint8_t ep, uint32_t nbytes)
{
    //USB_LOG_RAW("actual in len:%d\r\n", nbytes);
    //rt_kprintf("in tx len:%d\r\n", nbytes);

    if ((nbytes % CDC_MAX_MPS) == 0 && nbytes) {
        /* send zlp */
        usbd_ep_start_write(CDC_IN_EP, NULL, 0);
    } else {
        ep_tx_busy_flag = false;
        rt_sem_release(&cdc_tx_sem);
    }
}

/*!< endpoint call back */
struct usbd_endpoint cdc_out_ep = {
    .ep_addr = CDC_OUT_EP,
    .ep_cb = usbd_cdc_acm_bulk_out
};

struct usbd_endpoint cdc_in_ep = {
    .ep_addr = CDC_IN_EP,
    .ep_cb = usbd_cdc_acm_bulk_in
};

struct usbd_interface intf0 = {0};
struct usbd_interface intf1 = {0};

struct rt_device *rtdevice_cdc = {0};

rt_err_t rt_hw_vcom_register(struct rt_device *device, const char *name, rt_uint32_t flag, void *data);

void cdc_acm_init(void)
{
    rt_sem_init(&cdc_tx_sem, "tx", 0, RT_IPC_FLAG_FIFO );
    rt_sem_init(&cdc_rx_sem, "rx", 0, RT_IPC_FLAG_FIFO );
    rt_ringbuffer_init(&cdc_rx_ringbuffer, cdc_rx_ringbuffer_pool, sizeof(cdc_rx_ringbuffer_pool) );

    usbd_desc_register(cdc_descriptor);

//    usbd_msosv1_desc_register("123");
//    usbd_msosv2_desc_register("456");
//    usbd_bos_desc_register("789");

    usbd_add_interface(usbd_cdc_acm_init_intf(&intf0));
    usbd_add_interface(usbd_cdc_acm_init_intf(&intf1));
    usbd_add_endpoint(&cdc_out_ep);
    usbd_add_endpoint(&cdc_in_ep);
    usbd_initialize();

    rt_hw_vcom_register(&rtdevice_cdc, "vcom", 0, NULL);
}

void usbd_cdc_acm_set_line_coding(uint8_t intf, struct cdc_line_coding *line_coding)
{
    rt_kprintf("cdc set line coding： %d %d %d %d\n",
            line_coding->dwDTERate,
            line_coding->bCharFormat,
            line_coding->bParityType,
            line_coding->bDataBits);
}

volatile uint8_t dtr_enable = 0;
volatile uint8_t rts_enable = 0;

void usbd_cdc_acm_set_dtr(uint8_t intf, bool dtr)
{
    if (dtr) {
        dtr_enable = 1;
    } else {
        dtr_enable = 0;
    }
    rt_kprintf("cdc dtr： %d\n",dtr);
}

void usbd_cdc_acm_set_rts(uint8_t intf, bool rts)
{
    if (rts) {
        rts_enable = 1;
    } else {
        rts_enable = 0;
    }
    rt_kprintf("cdc rts： %d\n",rts);
}

//void cdc_acm_data_send_with_dtr(uint8_t *buffer, uint16_t len)
//{
//    if (dtr_enable) {
//        ep_tx_busy_flag = true;
//        memcpy(usb_cdc_write_buffer, buffer, len);
//        usbd_ep_start_write(CDC_IN_EP, usb_cdc_write_buffer, len);
//        while (ep_tx_busy_flag) {
//        }
//    }
//}

int cdc_acm_data_write(uint8_t *buffer, uint16_t len)
{
    //if (dtr_enable)
    {
        rt_sem_control(&cdc_tx_sem, RT_IPC_CMD_RESET, NULL);
        memcpy(usb_cdc_write_buffer, buffer, len);
        usbd_ep_start_write(CDC_IN_EP, usb_cdc_write_buffer, len);
        rt_sem_take(&cdc_tx_sem, 1000);
    }
    return len;
}

int cdc_acm_data_read(uint8_t *buffer, uint16_t len)
{
    return rt_ringbuffer_get(&cdc_rx_ringbuffer, buffer, len);
}

int cdc_acm_data_wait(int32_t timeout)
{
    return rt_sem_take(&cdc_rx_sem, timeout);
}




static rt_err_t rt_vcom_init(struct rt_device *dev)
{
    return RT_EOK;
}

static rt_err_t rt_vcom_open(struct rt_device *dev, rt_uint16_t oflag)
{
    return RT_EOK;
}


static rt_err_t rt_vcom_close(struct rt_device *dev)
{
    return RT_EOK;
}


static rt_size_t rt_vcom_read(struct rt_device *dev, rt_off_t          pos, void             *buffer, rt_size_t         size)
{
    return cdc_acm_data_read(buffer,size);
}


static rt_size_t rt_vcom_write(struct rt_device *dev, rt_off_t          pos, const void       *buffer, rt_size_t         size)
{
    return cdc_acm_data_write(buffer,size);
}

static rt_err_t rt_vcom_control(struct rt_device *dev, int cmd, void *args)
{
    return RT_EOK;
}


rt_err_t rt_hw_vcom_register(struct rt_device *device, const char              *name, rt_uint32_t              flag, void                    *data)
{
    rt_err_t ret;

    device->type        = RT_Device_Class_Char;
    device->rx_indicate = RT_NULL;
    device->tx_complete = RT_NULL;

#ifdef RT_USING_DEVICE_OPS
    device->ops         = &serial_ops;
#else
    device->init        = rt_vcom_init;
    device->open        = rt_vcom_open;
    device->close       = rt_vcom_close;
    device->read        = rt_vcom_read;
    device->write       = rt_vcom_write;
    device->control     = rt_vcom_control;
#endif
    device->user_data   = data;

    /* register a character device */
    ret = rt_device_register(device, name, flag);

#ifdef RT_USING_POSIX_STDIO
    /* set fops */
    device->fops        = &_serial_fops;
#endif
    return ret;
}






